package labox.innovation.loginserver.loginserverpackets;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * This class ...
 *
 * @version $Revision: 1.2.4.1 $ $Date: 2005/03/27 15:30:11 $
 */
public abstract class ServerBasePacket {
	ByteArrayOutputStream _bao;

	protected ServerBasePacket() {
		_bao = new ByteArrayOutputStream();
	}

	protected void writeInt(int value) {
		_bao.write(value & 0xff);
		_bao.write(value >> 8 & 0xff);
		_bao.write(value >> 16 & 0xff);
		_bao.write(value >> 24 & 0xff);
	}

	protected void writeShort(int value) {
		_bao.write(value & 0xff);
		_bao.write(value >> 8 & 0xff);
	}

	protected void writeByte(int value) {
		_bao.write(value & 0xff);
	}

	protected void writeDouble(double org) {
		long value = Double.doubleToRawLongBits(org);
		_bao.write((int) (value & 0xff));
		_bao.write((int) (value >> 8 & 0xff));
		_bao.write((int) (value >> 16 & 0xff));
		_bao.write((int) (value >> 24 & 0xff));
		_bao.write((int) (value >> 32 & 0xff));
		_bao.write((int) (value >> 40 & 0xff));
		_bao.write((int) (value >> 48 & 0xff));
		_bao.write((int) (value >> 56 & 0xff));
	}

	protected void writeString(String text) {
		try {
			if (text != null) {
				_bao.write(text.getBytes("UTF-16LE"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		_bao.write(0);
		_bao.write(0);
	}

	protected void writeBytes(byte[] array) {
		try {
			_bao.write(array);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public byte[] getBytes() {
		writeInt(0x00); //为后面的校验码预留4字节
		return _bao.toByteArray();
	}

	public abstract byte[] getContent() throws IOException;
}
